package reflect;

import java.lang.reflect.Field;

public class ReflectDemo8 {
    public static void main(String[] args) throws NoSuchFieldException, InstantiationException, IllegalAccessException, ClassNotFoundException {
        Class cls = Class.forName("reflect.Person");
        Object obj = cls.newInstance();

        Field field = cls.getDeclaredField("name");//获取name属性
        field.setAccessible(true);//强制打开访问权限
        field.set(obj,"张三");//obj.name="张三";
        String name = (String)field.get(obj);//String name = obj.name;
        System.out.println("姓名:"+name);
        field.setAccessible(false);//关闭房间权限

        Field field1 = cls.getDeclaredField("age");//获取age属性
        field1.setAccessible(true);
        field1.set(obj,25);//obj.age=25;
        int age = (int)field1.get(obj);//int age = obj.age;
        System.out.println("年龄:"+age);
        field1.setAccessible(false);

        System.out.println(obj);
    }
}
